#include "../server.hpp"

std::unordered_map<uint64_t, PtrConnection> _conns;
uint64_t connid = rand() % 10000; 
EventLoop base_loop; 
LoopThreadPool *loop_pool;

void OnMessage(const PtrConnection& conn, Buffer* buf)
{
    DBG_LOG("%s", buf->ReaderPosition());
    buf->MoveReadOffset(buf->ReadAbleSize());
    std::string str = "hello world";
    conn->Send(str.c_str(), str.size());
} 
void ConnectionDestory(const PtrConnection& conn)
{
    _conns.erase(conn->Id());
}
void OnConnected(const PtrConnection& conn)
{
    DBG_LOG("New Connection: %p", conn.get());
}
void NewConnection(int fd)
{
    connid++;
    PtrConnection conn(new Connection(loop_pool->NextLoop(), connid, fd));
    conn->SetMessageCallback(std::bind(OnMessage, std::placeholders::_1, std::placeholders::_2));
    conn->SetConnectedCallback(std::bind(OnConnected, std::placeholders::_1));
    conn->SetSrvClosedCallback(std::bind(ConnectionDestory, std::placeholders::_1));
    
    conn->EnableInactiveRelease(10); // 启动非活跃超时销毁
    conn->Established(); // 就绪初始化
    _conns.insert({connid, conn});

    DBG_LOG("New ----------------");

}
int main()
{
    loop_pool = new LoopThreadPool(&base_loop);
    loop_pool->SetThreadCount(2);
    loop_pool->Create();
    
    Acceptor acceptor(&base_loop, 8080);
    acceptor.SetAcceptCallback(std::bind(NewConnection, std::placeholders::_1));
    acceptor.Listen();
    
    base_loop.Start();

    return 0;
}